/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhndt.audiobook.ui;

import com.anhndt.audiobook.business.CenterLayout;
import com.anhndt.audiobook.ui.renderer.ItemRendererImpl;
import com.anhndt.audiobook.business.Resource;
import com.anhndt.audiobook.entity.ItemEntity;
import com.anhndt.audiobook.iface.ProcessListener;
import com.anhndt.audiobook.parser.ItemParser;
import com.anhndt.audiobook.ui.MainForm.ItemTopHit;
import com.anhndt.audiobook.utils.DialogUtil;
import com.anhndt.audiobook.utils.StringUtil;
import com.anhndt.audiobook.utils.Util;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Graphics;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.layouts.GridLayout;
import com.sun.lwuit.list.DefaultListModel;
import com.sun.lwuit.plaf.UIManager;
import java.util.Vector;

/**
 *
 * @author Sun
 */
public class MainForm extends BaseForm {

    private List listTopHit;
    Button mButtonCategory;
    Button mButtonFavorite;
    Button mButtonSearch;
    Button mButtonResume;
    Command mCommandSetting;
    String selectCommandTextButton;
    public static ItemEntity mItemRoot, mItemTopHit;
    public static int sizeDisplayHit;
    static BaseForm mMainScreen;

    static {
        resetRoot();
    }

    static void resetRoot() {
        if (mItemRoot == null) {
            mItemRoot = new ItemEntity();
        } else {
            mItemRoot.removeAllChilrends();
        }
        mItemRoot.id = "1";
        mItemRoot.typeEntity = ItemEntity.TYPE_CATEGORY;
    }

    public static BaseForm getMainScreen() {
        return mMainScreen;
    }

    public static void showMainScreen() {
        if (mMainScreen != null) {
            mMainScreen.show();
        }
    }

    public MainForm() {
        super(Resource.APP_TITLE, null, null);
        mMainScreen = this;
        cmdView = null;
        //test
//        ItemEntity entity = new ItemEntity();
//        entity.id = "11";
//        entity.typeEntity = 2;
//        
//        ItemParser parserArticlePart = new ItemParser(entity, null, null, null, false);
//        getResponseItem(entity, parserArticlePart, null);
    }

    protected void releaseAll() {
        if (mItemRoot != null) {
            mItemRoot.removeAllIconOfChild("" + ItemEntity.TYPE_ARTICLE);
        }
        mButtonCategory = mButtonFavorite = mButtonResume = mButtonSearch = null;
        listTopHit = null;
        cmdBack = null;
        super.releaseAll();
    }

    public static ItemEntity getRoot() {
        return mItemRoot;
    }

    protected void init() {
        Display.getInstance().setThirdSoftButton(true);
        if (StringUtil.isNullOrEmpty(selectCommandTextButton)) {
            selectCommandTextButton = Resource.BUTTON_CATEGORY;
        }
        super.init();

        //create home button
        mButtonCategory = createHomeButton(Util.getImage("category"), Util.getImage("category_selected"), Resource.BUTTON_CATEGORY);
        mButtonFavorite = createHomeButton(Util.getImage("home_favorite"), Util.getImage("home_favorite_selected"), Resource.BUTTON_FAVORITE);
        mButtonSearch = createHomeButton(Util.getImage("search"), Util.getImage("search_selected"), Resource.BUTTON_SEARCH);
        mButtonResume = createHomeButton(Util.getImage("home_play"), Util.getImage("home_play_selected"), Resource.BUTTON_RESUME);

        Container conButton = new Container(new GridLayout(1, 4));
        conButton.setUIID("PanelHomeButton");
        conButton.getUnselectedStyle().setMargin(Container.BOTTOM, 4);
        conButton.addComponent(mButtonCategory);
        conButton.addComponent(mButtonSearch);
        conButton.addComponent(mButtonFavorite);
        conButton.addComponent(mButtonResume);
        body.addComponent(BorderLayout.SOUTH, conButton);
        conButton.invalidate();

        mCommandSetting = new Command(Resource.CMD_SETTING);
        form.addCommand(new Command(Resource.CMD_ABOUT));
        form.addCommand(mCommandSetting);
        form.addCommand(new Command(Resource.CMD_LOGOUT));
        //calculate sizeDisplayHit
        sizeDisplayHit = form.getPreferredH() - getTitleBarHeight() - getMenubarHeight() - mButtonCategory.getParent().getPreferredH();

        updateFocus();
        loadTopHit();
    }

    /**
     * update focus when user back to main screen
     */
    void updateFocus() {
        if (selectCommandTextButton.equals(Resource.BUTTON_CATEGORY)) {
            form.setFocused(mButtonCategory);
        } else if (selectCommandTextButton.equals(Resource.BUTTON_FAVORITE)) {
            form.setFocused(mButtonFavorite);
        } else if (selectCommandTextButton.equals(Resource.BUTTON_RESUME)) {
            form.setFocused(mButtonResume);
        } else if (selectCommandTextButton.equals(Resource.BUTTON_SEARCH)) {
            form.setFocused(mButtonSearch);
        }
    }

    private void loadTopHit() {
        final int sizeThumbHit = Util.sizeThumbHit - 2 * 5;
        if (mItemTopHit == null) {
            mItemTopHit = new ItemEntity();
            mItemTopHit.typeEntity = ItemEntity.TYPE_HIT;
            
            ProcessListener callback = new ProcessListener() {

                public void onSuccess(Object result, int index) {
                    bindTopHit();
                    loadThumb(mItemTopHit.getItemChildrends("" + ItemEntity.TYPE_ARTICLE), sizeThumbHit, sizeThumbHit, "hit", false);
                }

                public void onError(String status, int index) {
                }
            };
            ItemParser parserTopHit = new ItemParser(Util.userID, null, null, "" + ItemEntity.TYPE_HIT, null, null, null, true);
            getResponseItem(mItemTopHit, parserTopHit, callback, false);
        } else {
            bindTopHit();
            loadThumb(mItemTopHit.getItemChildrends("" + ItemEntity.TYPE_ARTICLE), sizeThumbHit, sizeThumbHit, "hit", false);
        }
    }

    void loadThumbHit() {
        int size = Util.sizeThumbHit - 2 * UIManager.getInstance().getComponentStyle("Hit").getBorder().getThickness();
        loadThumb(mItemTopHit.getItemChildrends("" + ItemEntity.TYPE_ARTICLE), size, size, "hit", false);
    }

    void bindTopHit() {
        Vector vtTopHit = (mItemTopHit != null) ? mItemTopHit.getItemChildrends("" + ItemEntity.TYPE_ARTICLE) : null;
        if (vtTopHit != null && vtTopHit.size() > 0) {
            //create ListTopHit
            if (listTopHit == null) {
                final ItemTopHit renderer = new ItemTopHit();
                listTopHit = new ListItem(vtTopHit) {

                    protected void focusGained() {
                        super.focusGained();
                        renderer.onFocusGainded();
                    }

                    protected void focusLost() {
                        super.focusLost();
                        renderer.onFocusLost();
                    }
                };
                listTopHit.setOrientation(List.HORIZONTAL);
                listTopHit.setFixedSelection(List.FIXED_NONE_CYCLIC);
                listTopHit.setListCellRenderer(renderer);
                listTopHit.addActionListener(this);
                body.addComponent(BorderLayout.CENTER, listTopHit);
            } else {
                listTopHit.setModel(new DefaultListModel(vtTopHit));
            }
            form.repaint();
        }
    }

    void bindNotify() {
        Vector notifies = (mItemTopHit != null) ? mItemTopHit.getItemChildrends("" + ItemEntity.TYPE_NOTIFY) : null;
        String notify = (notifies != null && notifies.size() > 0) ? notifies.elementAt(0).toString() : null;
        DialogUtil.showDialog(notify, DialogUtil.ONE_BUTTON, new String[]{Resource.CMD_OK}, Dialog.TYPE_ALARM);
    }

    private Button createHomeButton(Image defaultIcon, Image rolloverIcon, String selectCommandText) {
        Button btn = new Button(defaultIcon);
        btn.setUIID("MainButton");
        btn.setAlignment(Button.CENTER);
        btn.setRolloverIcon(rolloverIcon);
        btn.addActionListener(this);
        btn.setSelectCommandText(selectCommandText);
        return btn;
    }

    protected void backScreen() {
        AudioStore.exitApp();
    }

    public void actionPerformed(ActionEvent evt) {
        Object source = evt.getSource();
        Command cmd = evt.getCommand();
        if (cmd == mCommandSetting) {
            formChild = new SettingForm(this);
            showFormChild(formChild);
        } else if (cmd != null && cmd.getCommandName().equals(Resource.CMD_ABOUT)) {
            Display.getInstance().setThirdSoftButton(false);
            new About(form).show();
        } else if (cmd != null && cmd.getCommandName().equals(Resource.CMD_LOGOUT)) {
            Display.getInstance().setThirdSoftButton(false);
            new LoginForm(MainForm.this).show();
        } else if (source instanceof Button) {
            actionButton((Button) source);
        } else if (source == listTopHit) {
            final ItemEntity selectedItem = (ItemEntity) listTopHit.getSelectedItem();
            //create callback
            ProcessListener callback = new ProcessListener() {

                public void onSuccess(Object result, int index) {
//                    Vector vtAdvText = (Vector) selectedItem.getItemChildrends("" + ItemEntity.TYPE_ADVERTISE_TEXT);
//                    String advText = vtAdvText.size() > 0 ? vtAdvText.elementAt(0).toString() : title;

                    Vector articleParts = (Vector) selectedItem.getItemChildrends("" + ItemEntity.TYPE_ARTICLE_PART);
                    //neu chi co 1 articlepart thi show man hinh MediaPlayer ngay
                    int size = articleParts.size();
                    if (size == 1) {
                        formChild = new MediaPlayerForm(selectedItem.name, MainForm.this, selectedItem, 0);
                    } else if (size > 1) {
                        formChild = new ArticlePartForm(selectedItem.name, MainForm.this, selectedItem, selectedItem);
                    } else if (listItem != null) {
                        listItem.setHandlesInput(true);
                    }
                    showFormChild(formChild);
                }

                public void onError(String status, int index) {
                }
            };
            selectedItem.changeMarked(true);
            //set lastIdArticle
            Util.lastArticleID = selectedItem.id;
            ItemParser parserArticlePart = new ItemParser(selectedItem, null, null, null, false);
            getResponseItem(selectedItem, parserArticlePart, callback);
        }
    }

    void actionButton(Button source) {
        if (selectCommandTextButton != null && !selectCommandTextButton.equals(source.getSelectCommandText())) {
            resetRoot();
        }
        selectCommandTextButton = source.getSelectCommandText();

        if (source == mButtonCategory) {
            //create callback
            ProcessListener callback = new ProcessListener() {

                public void onSuccess(Object result, int index) {
//                    Vector vtAdvText = (Vector) root.getValue("" + ItemEntity.TYPE_ADVERTISE_TEXT);
//                    String advText = vtAdvText.size() > 0 ? vtAdvText.elementAt(0).toString() : null;
                    formChild = new CategoryForm(mItemRoot.name, MainForm.this, mItemRoot);
                    showFormChild(formChild);
                }

                public void onError(String status, int index) {
                }
            };
            ItemParser parserCategory = new ItemParser(mItemRoot);
            getResponseItem(mItemRoot, parserCategory, callback);
        } else if (source == mButtonFavorite) {
            favorite();
        } else if (source == mButtonSearch) {
            mItemRoot.typeEntity = ItemEntity.TYPE_ARTICLE;
            formChild = new CategoryForm(TAG_SEARCH, null, this, mItemRoot);
//            formChild = new ArticleForm(TAG_SEARCH, null, this, root, true);
            showFormChild(formChild);
        } else if (source == mButtonResume) {
            playLastArticle();
        }
    }

    void favorite() {
        mItemRoot.typeEntity = ItemEntity.TYPE_FAVORITE_LIST;
        ProcessListener callback = new ProcessListener() {

            public void onSuccess(Object result, int index) {
                if (mItemRoot.getItemChildrends("" + ItemEntity.TYPE_ARTICLE).size() <= 0) {
                    DialogUtil.showInfoDialog(Resource.TXT_NO_RESULT, true);
                    return;
                }
                try {
                    int counter = mItemRoot.getFirstItem("" + ItemEntity.TYPE_COUNTER_ITEM).counterChild;
                    mItemRoot.counterChild = counter;
                } catch (Exception e) {
                }
                formChild = new ArticleForm(TAG_FAVORITE, mItemRoot.name, MainForm.this, mItemRoot);
                formChild.setSupportSearch(false);
                showFormChild(formChild);
            }

            public void onError(String status, int index) {
            }
        };
        ItemParser paserFavorite = new ItemParser(mItemRoot, null, "" + Util.displayCounter, "1", true);
        getResponseItem(mItemRoot, paserFavorite, callback);
    }

    void playLastArticle() {
        System.out.println("playLastArticle : " + Util.lastArticleID);
        if (StringUtil.isNullOrEmpty(Util.lastArticleID)) {
            DialogUtil.showWarningDialog(Resource.TXT_WARRING_NO_HAVE_ARTICLE);
            return;
        }
        mItemRoot.typeEntity = ItemEntity.TYPE_ARTICLE;
        mItemRoot.id = Util.lastArticleID;
//        root = Util.lastArticle.clone();

        //create callback
        ProcessListener callback = new ProcessListener() {

            public void onSuccess(Object result, int index) {
                //neu co du lieu, thi hien thi man hinh ArticlePartForm
                Vector articleParts = (Vector) mItemRoot.getItemChildrends("" + ItemEntity.TYPE_ARTICLE_PART);
                //neu chi co 1 articlepart thi show man hinh MediaPlayer ngay
                int size = articleParts.size();
                if (size == 1) {
                    formChild = new MediaPlayerForm("", MainForm.this, mItemRoot, 0);
                } else if (size > 1) {
                    ItemEntity entityArticle = mItemRoot.getFirstItem("" + ItemEntity.TYPE_ARTICLE);
                    ItemEntity counterItem = mItemRoot.getFirstItem("" + ItemEntity.TYPE_COUNTER_ITEM);
                    if (counterItem != null) {
                        entityArticle.counterChild = counterItem.counterChild;
                        entityArticle.description = entityArticle.counterChild + " phần";
                    }
                    formChild = new ArticlePartForm("", MainForm.this, mItemRoot, entityArticle);
                }
                showFormChild(formChild);
            }

            public void onError(String status, int index) {
            }
        };
        //get response
        ItemParser parserLastArticle = new ItemParser(mItemRoot);
        getResponseItem(mItemRoot, parserLastArticle, callback);
    }

    class ItemTopHit extends ItemRendererImpl {

        Label rotateExpand;

        public ItemTopHit() {
            super();
            setFocusable(false);
            getUnselectedStyle().setBorder(null);
            getSelectedStyle().setBorder(null);
        }

        protected void createThumb() {
            super.createThumb();
            thumb.setPreferredSize(new Dimension(Util.sizeThumbHit, Util.sizeThumbHit));
            thumb.setSize(new Dimension(Util.sizeThumbHit, Util.sizeThumbHit));
            thumb.setAlignment(Button.CENTER);
            thumb.setFocusable(true);
            thumb.setUIID("Hit");
        }

        void onFocusGainded() {
            thumb.setFocus(true);
        }

        void onFocusLost() {
            thumb.setFocus(false);
        }

        protected void paintBackground(Graphics g) {
//            super.paintBackground(g);
        }

        protected void addingComponent() {
            panel = new Container(new BorderLayout());
            if (thumb == null) {
                createThumb();
            }
            int deviceDesity = Util.getDeviceDensity();
            if (deviceDesity > Util.DENSITY_LOW) {
                //bo tri theo chieu ngang
                addingComponent(panel);
                addThumb();
            } else {
                //bo tri theo chieu doc
                panel.setLayout(new CenterLayout());
                panel.addComponent(thumb);
                panel.addComponent(rate);
                panel.addComponent(lblName);
                panel.addComponent(lblDescription);
            }
            addComponent(BorderLayout.CENTER, panel);
            panel.getUnselectedStyle().setMargin(TOP, getMarginTop());
        }

        int getMarginTop() {
            int deviceDesity = Util.getDeviceDensity();
            if (deviceDesity > Util.DENSITY_LOW) {
                return (sizeDisplayHit - Util.sizeThumbHit) / 2;
            } else {
                return (sizeDisplayHit - rate.getPreferredH() - Util.sizeThumbHit - lblName.getStyle().getFont().getHeight() - lblDescription.getStyle().getFont().getHeight()) / 4;
            }
        }

        public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected) {
            return super.getListCellRendererComponent(list, value, index, false); //allway not selected
        }
    }

    class About extends Form {

        public About(final Form parent) {
            super(null);
            setLayout(new BorderLayout());
            addCommand(new Command(Resource.CMD_BACK) {

                public void actionPerformed(ActionEvent evt) {
                    parent.show();
                }
            });
            setBackCommand(getCommand(0));
            Label lblLogo = new Label(Util.getImageAsResource("logo"));
            lblLogo.setAlignment(Component.CENTER);
            lblLogo.getStyle().setBgTransparency(0);

            Label lblAppName = new Label(Resource.TXT_ABOUT);
            lblAppName.getStyle().setFont(Util.getBoldFont());
            lblAppName.setAlignment(Component.CENTER);

            Label lblSupport = new Label(Resource.TXT_SUPPORT);
            lblSupport.getStyle().setFont(Util.getNormalFont());
            lblSupport.setAlignment(Component.CENTER);

            Label lblCopyRight = new Label("© 2011 AudioStore");
            lblCopyRight.getStyle().setFont(Util.getNormalFont());
            lblCopyRight.setAlignment(Component.CENTER);

            Container panelInfo = new Container(new BoxLayout(BoxLayout.Y_AXIS));
            panelInfo.addComponent(lblAppName);
            panelInfo.addComponent(lblSupport);
            panelInfo.addComponent(lblCopyRight);

            addComponent(BorderLayout.CENTER, lblLogo);
            addComponent(BorderLayout.SOUTH, panelInfo);
        }
    }
}
